<template>
	<div class="test-env-container">
		<!-- 左侧环境列表 -->
		<div class="env-sidebar">
			<div class="sidebar-header">
				<div class="sidebar-title">
					<el-icon><Monitor /></el-icon>
					<h2>测试环境</h2>
				</div>
				<el-tooltip content="添加新测试环境" placement="right" effect="light">
					<el-button 
						@click="addEnv" 
						type="primary" 
						class="add-env-btn"
						round
						:icon="Plus">
						添加环境
					</el-button>
				</el-tooltip>
			</div>
			<el-scrollbar class="env-list-scrollbar">
				<div class="env-list">
					<template v-if="testEnvs.length > 0">
						<div 
							v-for="item in testEnvs" 
							:key="item.id"
							@click="selectEnv(item)"
							class="env-item"
							:class="{ 'env-item-active': active === item.id.toString() }">
							<div class="env-icon">
								<el-icon><Connection /></el-icon>
							</div>
							<span class="env-name">{{ item.name }}</span>
						</div>
					</template>
					<div v-else class="env-list-empty">
						<el-empty :image-size="64" description="无环境配置"></el-empty>
					</div>
				</div>
			</el-scrollbar>
		</div>

		<!-- 右侧内容区 -->
		<div class="main-content">
			<template v-if="EnvInfo">
				<div class="env-header">
					<div class="env-header-info">
						<div class="env-title">
							<el-icon><Monitor /></el-icon>
							<h2>{{ EnvInfo.name }}</h2>
						</div>
						<div class="env-subtitle">
							<el-icon><Link /></el-icon>
							<span>{{ EnvInfo.host || '未设置服务器地址' }}</span>
						</div>
					</div>
					<div class="env-actions">
						<el-button-group>
							<el-tooltip content="保存环境配置" placement="top">
								<el-button @click="saveEnv" type="primary" :icon="Check">保存</el-button>
							</el-tooltip>
							<el-tooltip content="复制环境配置" placement="top">
								<el-button @click="copyEnv" type="info" :icon="CopyDocument">复制</el-button>
							</el-tooltip>
							<el-tooltip content="删除环境配置" placement="top">
								<el-button @click="delEnv" type="danger" :icon="Delete">删除</el-button>
							</el-tooltip>
						</el-button-group>
					</div>
				</div>

				<!-- 主要内容区域，使用el-scrollbar确保内容可滚动 -->
				<el-scrollbar class="env-content-scroll">
					<div class="env-content">
						<!-- 基本配置信息 -->
						<el-card class="config-card">
							<template #header>
								<div class="card-header">
									<el-icon><InfoFilled /></el-icon>
									<span>基本信息</span>
								</div>
							</template>
							<div class="form-group">
								<el-input v-model="EnvInfo.name" placeholder="环境名称" size="default">
									<template #prepend>
										<el-icon><EditPen /></el-icon>
										<span class="prepend-text">环境名称</span>
									</template>
								</el-input>
							</div>
							<div class="form-group">
								<el-input v-model="EnvInfo.host" placeholder="服务器域名或IP地址" size="default">
									<template #prepend>
										<el-icon><Link /></el-icon>
										<span class="prepend-text">服务器地址</span>
									</template>
								</el-input>
							</div>
						</el-card>

						<div class="config-grid">
							<!-- 环境配置卡片 -->
							<el-card class="config-card">
								<template #header>
									<div class="card-header">
										<el-icon><Setting /></el-icon>
										<span>环境配置</span>
									</div>
								</template>
								<el-tabs type="border-card" class="env-tabs" stretch v-model="headersActiveTab">
									<el-tab-pane label="全局请求头" name="headers">
										<div class="editor-wrapper">
											<Editor 
												v-model="EnvInfo.headers" 
												height="260px" 
												theme="chrome" 
												lang="json">
											</Editor>
										</div>
									</el-tab-pane>
									<el-tab-pane label="数据库配置" name="db">
										<div class="editor-wrapper">
											<Editor 
												v-model="EnvInfo.db" 
												height="260px" 
												theme="chrome" 
												lang="json">
											</Editor>
										</div>
									</el-tab-pane>
								</el-tabs>
							</el-card>

							<!-- 全局变量卡片 -->
							<el-card class="config-card">
								<template #header>
									<div class="card-header">
										<el-icon><Paperclip /></el-icon>
										<span>全局变量</span>
									</div>
								</template>
								<el-tabs type="border-card" class="env-tabs" stretch v-model="globalActiveTab">
									<el-tab-pane label="全局变量" name="global">
										<div class="editor-wrapper">
											<Editor 
												v-model="EnvInfo.global_variable" 
												height="260px" 
												theme="chrome" 
												lang="json">
											</Editor>
										</div>
									</el-tab-pane>
									<el-tab-pane label="调试运行变量" name="debug">
										<div class="editor-wrapper">
											<Editor 
												v-model="EnvInfo.debug_global_variable" 
												height="260px" 
												theme="chrome" 
												lang="json">
											</Editor>
										</div>
									</el-tab-pane>
								</el-tabs>
							</el-card>
						</div>

						<!-- 全局函数卡片 -->
						<el-card class="config-card function-card">
							<template #header>
								<div class="card-header">
									<el-icon><Star /></el-icon>
									<span>全局函数</span>
								</div>
							</template>
							<div class="editor-wrapper">
								<Editor 
									v-model="EnvInfo.global_func" 
									height="600px"
									lang="python" 
									theme="monokai">
								</Editor>
							</div>
						</el-card>
					</div>
				</el-scrollbar>
			</template>

			<!-- 空状态 -->
			<div class="env-empty" v-if="testEnvs.length === 0">
				<el-empty description="暂无测试环境">
					<el-button type="primary" @click="addEnv" round>
						<el-icon><Plus /></el-icon>
						<span>添加测试环境</span>
					</el-button>
				</el-empty>
			</div>
		</div>
	</div>
</template>

<script>
/*
功能实现:
	测试环境的增删查改
*/
import { mapState, mapActions, mapMutations } from 'vuex';
import Editor from '../components/common/Editor.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
	Check, 
	Delete, 
	CopyDocument, 
	EditPen, 
	Link, 
	Monitor, 
	Setting,
	Plus,
	Connection,
	CircleCheck,
	InfoFilled,
	Paperclip,
	Star
} from '@element-plus/icons-vue';

export default {
	components: {
		Editor,
		Check,
		Delete,
		CopyDocument,
		EditPen,
		Link,
		Monitor,
		Setting,
		Plus,
		Connection,
		CircleCheck,
		InfoFilled,
		Paperclip,
		Star
	},
	data() {
		return {
			active: '1',
			EnvInfo: null,
			headersActiveTab: 'headers',
			globalActiveTab: 'global'
		};
	},
	computed: {
		...mapState(['pro', 'testEnvs', 'envInfo'])
	},
	methods: {
		...mapActions(['getAllEnvs']),

		// 创建环境
		async addEnv() {
			const params = { project: this.pro.id, name: "新测试环境" }
			const response = await this.$api.createTestEnv(params);
			if (response.status === 201) {
				ElMessage({
					type: 'success',
					message: '添加成功',
					duration: 1000
				});
				await this.getAllEnvs();
				
				// 选中新创建的环境
				if (this.testEnvs.length > 0) {
					const newEnv = this.testEnvs.find(env => env.name === "新测试环境") || this.testEnvs[this.testEnvs.length - 1];
					this.selectEnv(newEnv);
				}
			}
		},
		// 删除环境
		async delEnv() {
			ElMessageBox.confirm('确定要删除该测试环境吗？此操作不可恢复。', '删除确认', {
				confirmButtonText: '确定删除',
				cancelButtonText: '取消',
				type: 'warning',
				draggable: true,
				closeOnClickModal: false
			})
				.then(async () => {
					const response = await this.$api.deleteTestEnv(this.EnvInfo.id);
					if (response.status === 204) {
						ElMessage({
							type: 'success',
							message: '删除成功',
							duration: 1000
						});
						await this.getAllEnvs();
						// 重新选中环境
						if (this.testEnvs.length > 0) {
							// 设置默认显示激活的测试场景
							this.active = this.testEnvs[0].id.toString();
							this.selectEnv(this.testEnvs[0]);
						} else {
							this.EnvInfo = null;
						}
					}
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消删除',
						duration: 1000
					});
				});
		},

		// 保存修改
		async saveEnv() {
			try {
				let params = {...this.EnvInfo}
				params.headers = JSON.parse(this.EnvInfo.headers);
				params.db = JSON.parse(this.EnvInfo.db);
				params.debug_global_variable = JSON.parse(this.EnvInfo.debug_global_variable);
				params.global_variable = JSON.parse(this.EnvInfo.global_variable);
				const response = await this.$api.updateTestEnv(params.id, params)
				if (response.status === 200) {
					ElMessage({
						type: 'success',
						message: '保存成功',
						duration: 1000
					});
					await this.getAllEnvs();
				}
			} catch (error) {
				ElMessage({
					type: 'error',
					message: 'JSON格式错误，请检查配置',
					duration: 2000
				});
			}
		},
		// 复制环境
		async copyEnv() {
			try {
				let params = {...this.EnvInfo}
				params.name = params.name + '_副本'
				params.headers = JSON.parse(this.EnvInfo.headers);
				params.db = JSON.parse(this.EnvInfo.db);
				params.debug_global_variable = JSON.parse(this.EnvInfo.debug_global_variable);
				params.global_variable = JSON.parse(this.EnvInfo.global_variable);
				const response = await this.$api.createTestEnv(params);
				if (response.status === 201) {
					ElMessage({
						type: 'success',
						message: '复制成功',
						duration: 1000
					});
					await this.getAllEnvs();
					
					// 选中新复制的环境
					if (this.testEnvs.length > 0) {
						const copyEnv = this.testEnvs.find(env => env.name === params.name) || this.testEnvs[this.testEnvs.length - 1];
						this.selectEnv(copyEnv);
					}
				}
			} catch (error) {
				ElMessage({
					type: 'error',
					message: 'JSON格式错误，请检查配置',
					duration: 2000
				});
			}
		},
		// 选中环境
		selectEnv(env) {
			this.active = env.id.toString()
			this.EnvInfo = { ...env };
			this.EnvInfo.headers = JSON.stringify(this.EnvInfo.headers, null, 4);
			this.EnvInfo.db = JSON.stringify(this.EnvInfo.db, null, 4);
			this.EnvInfo.debug_global_variable = JSON.stringify(this.EnvInfo.debug_global_variable, null, 4);
			this.EnvInfo.global_variable = JSON.stringify(this.EnvInfo.global_variable, null, 4);
		}
	},
	created() {
		this.getAllEnvs();
	},
	mounted() {
		if (this.testEnvs.length > 0) {
			if (this.envInfo) {
				this.selectEnv(this.envInfo);
			} else {
				// 设置默认选中的测试场景
				this.selectEnv(this.testEnvs[0]);
			}
		}
	}
};
</script>

<style scoped>
.test-env-container {
	display: flex;
	height: 100vh;
	background-color: #f5f7fa;
	position: relative;
	overflow: hidden;
}

/* 侧边栏样式 */
.env-sidebar {
	width: 240px;
	min-width: 240px;
	background-color: #fff;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
	z-index: 10;
	display: flex;
	flex-direction: column;
	height: 100%;
	overflow: hidden;
	border-right: 1px solid #ebeef5;
}

.sidebar-header {
	padding: 16px;
	display: flex;
	flex-direction: column;
	gap: 16px;
	border-bottom: 1px solid #f0f0f0;
	background-color: #f7f9fc;
}

.sidebar-title {
	display: flex;
	align-items: center;
	gap: 8px;
}

.sidebar-title h2 {
	margin: 0;
	font-size: 18px;
	font-weight: 600;
	color: #303133;
}

.add-env-btn {
	width: 100%;
}

.env-list-scrollbar {
	height: calc(100% - 95px);
	overflow: hidden;
}

.env-list {
	padding: 8px 0;
	min-height: 100%;
}

.env-list-empty {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 80%;
}

.env-item {
	display: flex;
	align-items: center;
	padding: 14px 16px;
	cursor: pointer;
	transition: all 0.3s;
	border-radius: 6px;
	margin: 4px 8px;
	background-color: #f7f8fa;
	border: 1px solid transparent;
}

.env-item:hover {
	background-color: #ecf5ff;
	border-color: #d9ecff;
	transform: translateY(-2px);
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.env-item-active {
	background-color: #ecf5ff;
	color: #409eff;
	font-weight: 500;
	border-left: 3px solid #409eff;
	box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.env-item-active:hover {
	background-color: #ecf5ff;
}

.env-icon {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 32px;
	height: 32px;
	border-radius: 8px;
	background-color: rgba(64, 158, 255, 0.1);
	margin-right: 12px;
	color: #409eff;
}

.env-name {
	flex: 1;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	font-size: 14px;
}

/* 主内容区域 */
.main-content {
	flex: 1;
	display: flex;
	flex-direction: column;
	height: 100%;
	position: relative;
	overflow: hidden;
}

/* 环境头部 */
.env-header {
	padding: 16px 24px;
	background-color: #fff;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	display: flex;
	justify-content: space-between;
	align-items: center;
	z-index: 5;
}

.env-header-info {
	display: flex;
	flex-direction: column;
	gap: 4px;
}

.env-title {
	display: flex;
	align-items: center;
	gap: 12px;
	margin-bottom: 4px;
}

.env-title h2 {
	margin: 0;
	font-size: 20px;
	font-weight: 600;
	color: #303133;
}

.env-subtitle {
	display: flex;
	align-items: center;
	gap: 8px;
	color: #909399;
	font-size: 13px;
}

.env-status {
	display: flex;
	align-items: center;
	gap: 4px;
}

.env-actions .el-button-group {
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	border-radius: 4px;
	overflow: hidden;
}

/* 内容滚动区 */
.env-content-scroll {
	flex: 1;
	overflow: hidden;
	height: calc(100% - 80px);
}

.env-content {
	padding: 16px 24px 32px;
}

/* 卡片样式 */
.config-card {
	margin-bottom: 20px;
	border-radius: 8px;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
	overflow: hidden;
}

.card-header {
	display: flex;
	align-items: center;
	gap: 8px;
	font-weight: 600;
	color: #303133;
	font-size: 16px;
}

.config-grid {
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
	gap: 20px;
	margin-bottom: 20px;
}

.form-group {
	margin-bottom: 16px;
}

.form-group:last-child {
	margin-bottom: 0;
}

.prepend-text {
	margin-left: 4px;
	white-space: nowrap;
}

.env-tabs {
	border-radius: 4px;
	overflow: hidden;
	border: none;
	box-shadow: none;
}

.editor-wrapper {
	border-radius: 4px;
	overflow: hidden;
	border: 1px solid #ebeef5;
}

.function-card .editor-wrapper {
	border: none;
}

/* 空状态 */
.env-empty {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	display: flex;
	justify-content: center;
	align-items: center;
	background-color: #fff;
}

/* 响应式调整 */
@media (max-width: 1400px) {
	.config-grid {
		grid-template-columns: 1fr;
	}
}

@media (max-width: 768px) {
	.env-sidebar {
		width: 200px;
		min-width: 200px;
	}
	
	.env-icon {
		width: 28px;
		height: 28px;
		margin-right: 8px;
	}
	
	.env-title h2 {
		font-size: 18px;
	}
}

/* 深色模式支持的预留样式 */
@media (prefers-color-scheme: dark) {
	/* 未来可添加深色模式样式 */
}

/* 滚动条美化 */
:deep(.el-scrollbar__bar) {
	opacity: 0.3;
}

:deep(.el-scrollbar__bar:hover) {
	opacity: 0.8;
}

:deep(.el-tabs__nav) {
	border: none !important;
}

:deep(.el-tabs--border-card) {
	background: #fff;
	border: none;
	box-shadow: none;
}

:deep(.el-tabs--border-card > .el-tabs__header) {
	background-color: #f7f9fc;
	border-bottom: 1px solid #f0f0f0;
}

:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active) {
	background-color: #ecf5ff;
	color: #409eff;
	border-right-color: #f0f0f0;
	border-left-color: #f0f0f0;
}

:deep(.el-card__header) {
	padding: 12px 16px;
	background-color: #f7f9fc;
}

:deep(.el-tag) {
	display: flex;
	align-items: center;
	gap: 4px;
}
</style>
